<?php
namespace app\common\customer\validate;


use think\Validate;
use think\validate\ValidateRule as Rule;

class CustomerContactValidate extends Validate
{
    protected $rule = [
        'id' => ['require', 'gt:0'],
        'member_id' => ['gt:0'],
        'contact_type' => ['require', 'gt:0'],
        'contact' => ['require','checkContact:mobile','unique:member_contact,contact_type^contact']
    ];

    protected $message = [
        'id.require' => '参数错误',
        'id.gt' => '请选择要修改的联系方式',
        'member_id.require' => '创建客资失败',
        'contact_type.require' => '请选择联系方式类型',
        'contact_type.gt' => '联系方式类型错误',
        'contact.require' => '联系方式不能为空',
        'contact.unique' => '已存在', // 配合controller提交的
        'contact.checkContact' => '联系方式格式不正确'
    ];

    protected $scene = [
        'create' => ['contact_type', 'contact'],
        'edit' => ['id', 'member_id','contact_type', 'contact'],
        'delete' => ['id']
    ];

    protected function checkContact($value, $rule, $data) {

        $validRes = false;
        switch ($data['contact_type']) {
            case 1: // 电话
                $validRes = $this->checkRule($value, ['mobile']);
                break;
            case 2: // 微信
                $validRes = true;
                break;
            case 3: // 座机
                $regex = '/^\d{3,4}-\d{7,8}(-\d{1,6})?$/';
                $validRes = preg_match($regex, $value) === false ? false : true;
                break;
        }

        return $validRes;
    }

}